<template>
  <div class="vue-box" style="display: none;" :style="'display: block;'">
    <div style="">
      <el-container>
        <!--左边栏，用户列表-->
        <el-aside width="300px">
          <div style="display: flex;
          height: 95vh;flex-direction: column;">
            <div>
              <div style="display: flex;justify-content: center">
                <el-badge type="success" is-dot class="badge-item">
                  <el-avatar v-if="selfUser.avatar !== ''" :src="selfUser.avatar"></el-avatar>
                </el-badge>
              </div>
              <div style="text-align: center">
                <div style="">{{ selfUser.username }}</div>
                <div style="font-size: smaller">{{ selfUser.remark }}</div>
              </div>
              <div style="font-size: 18px;text-align: center">联系人</div>
              <div style="text-align: center">
                <el-input
                    placeholder="搜索用户"
                    v-model="p.username">
                  <i slot="prefix" class="el-input__icon el-icon-search"></i>
                </el-input>
              </div>
            </div>
            <div class="user-list" style="overflow-y: auto;height: 100%">
              <div class="user-item" v-for="user in userList" :key="user.id"
                   @click="userClick(user);user.noReadNum > 0? online():''"
                   :id="user.id">
                <el-badge :type="user.userStatus === 'online' ?'success': 'info'" is-dot class="badge-item">
                  <el-avatar :src="sa.getImgPath(user.avatar)"></el-avatar>
                </el-badge>
                <div style="padding-left: 5px;flex: content">
                  <div style="">{{ user.username }}</div>
                  <div style="font-size: smaller">{{ user.lastMsg }}</div>
                </div>
                <div style="text-align: center; font-size: smaller;margin: 2px">
                  <div>
                    {{ user.lastSendTime }}
                  </div>
                  <div v-if="user.noReadNum > 0"
                       style="border-radius: 30px;width: 20px;background-color: hotpink">
                    {{ user.noReadNum }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-aside>
        <!--聊天界面-->
        <el-main v-loading="state.loading">
          <div style="display: flex;flex-direction: column;overflow: hidden;
          justify-content: space-between;height: calc(95vh - 20px);">
            <!--头-->
            <div style="display: flex;align-items: center;"
                 v-if="userInfo.avatar !== ''">
              <el-badge :type="userInfo.userStatus === 'online'?'success': 'info'"
                        is-dot class="badge-item">
                <el-avatar :src="sa.getImgPath(userInfo.avatar)"></el-avatar>
              </el-badge>
              <div style="font-size: initial;
              margin-left: 5px;
              flex: content">{{ userInfo.username }}
              </div>
              <div>更多操作</div>
            </div>
            <div v-else style="display: flex;align-items: center;height: 48px">
              暂无会话
            </div>
            <!--聊天记录-->
            <div style="overflow-y: auto;background-color: #e1dfdf; 
                        height: calc(95vh - 37px);border-radius: 5px"
                 id="msg-body">
              <div v-for="msg in msgList" :key="msg.id">
                <div v-if="msg.type === 'other' && msg.msgType === 'text'" style="display: flex;padding: 5px">
                  <div>
                    <el-avatar :src="sa.getImgPath(userInfo.avatar)"></el-avatar>
                  </div>
                  <div style="border-radius: 5px;margin-right: 40px;background-color: #efe7e7"> 
                    <div style="margin: 10px">
                      {{ msg.content }}
                    </div>
                  </div>
                </div>
                <div style="display: flex;padding: 5px;flex-direction: row-reverse"
                     v-if="msg.type === 'self' && msg.msgType === 'text'">
                  <div>
                    <el-avatar :src="selfUser.avatar"></el-avatar>
                  </div>
                  <div style="border-radius: 5px;margin-left: 40px;background-color: #a2e7f1">
                    <div style="margin: 10px">
                      {{ msg.content }}
                    </div>
                  </div>
                </div>
                <!--对方-->
                <div style="display: flex;padding: 5px" v-if="msg.type === 'other' && msg.msgType === 'img'">
                  <div>
                    <el-avatar :src="sa.getImgPath(userInfo.avatar)"></el-avatar>
                  </div>
                  <div style="border-radius: 5px;margin-right: 40px;background-color: #efe7e7">
                    <div style="margin: 10px;width:150px">
                      <el-image
                          class="chatImg"
                          :src="sa.getImgPath(msg.content)"
                          :preview-src-list="imgListAll">
                      </el-image>
                    </div>
                  </div>
                </div>
                <!--我方-->
                <div style="display: flex;padding: 5px;flex-direction: row-reverse" v-if="msg.type === 'self' && msg.msgType === 'img'">
                  <div>
                    <el-avatar :src="selfUser.avatar"></el-avatar>
                  </div>
                  <div style="border-radius: 5px;margin-left: 40px;background-color: #a2e7f1">
                    <div style="margin: 10px;width:150px" >
                      <el-image class="chatImg"
                          :src="sa.getImgPath(msg.content)" :preview-src-list="imgListAll">
                      </el-image>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <!--消息发送框-->
            <div>
              <div style="padding-bottom: 5px">
                <el-popover
                    placement="top-start" width="255" v-model="sendImgPopoverV" trigger="manual">
                  <div style="display: grid;height: 220px; overflow: auto;
                        align-content: center;grid-template-columns: repeat(4,25%);">
                    <div style="display: flex;align-items: center;cursor: pointer;margin: 5px;
                          height: 50px;background-color: beige;justify-content: center;">
                      <el-upload
                          :data="uploadData" :action="sendImgUrl" accept="image/*"
                          :before-upload="uploadBef" :on-success="uploadSuccess" :show-file-list="false">
                        <i class="el-icon-plus" title="选择发送图片"
                           style="font-size: 45px;"></i>
                      </el-upload>
                    </div>
                    <div class="icon-menu" @click="sendImg(item)"
                         style="display: flex;align-items: center;cursor: pointer;
                          padding: 5px;height: 50px;width:50px;justify-content: center;"
                         v-for="(item,index) in historyImg" :key="index">
                      <el-popover
                          placement="top-start" width="150" :open-delay="500"
                          :close-delay="100" trigger="hover">
                        <el-image
                            class="chatImg" :src="sa.getImgPath(item)"
                            fit="fill"></el-image>
                        <el-image slot="reference" style="width: 50px; height: 50px"
                                  :src="sa.getImgPath(item)" fit="fill"></el-image>
                      </el-popover>
                    </div>
                  </div>
                  <i @click="sendImgPopoverV? sendImgPopoverV= false:sendImgPopoverV=true" slot="reference"
                     class="el-icon-picture-outline-round up-img" title="发送图片" style="font-size: 30px;"></i>
                </el-popover>
              </div>
              <el-input
                  v-on:keyup.ctrl.enter.native="sendMsg()" type="textarea"
                  :autosize="{ minRows: 4, maxRows: 4}" placeholder="请输入内容" v-model="content">
              </el-input>
              <div style="padding-top: 5px;display: flex;justify-content: flex-end;align-items: center">
                <div style="font-size: small;color: #9F9F9F">Win:Win+.输入表情,Ctrl+Enter发送消息</div>
                <el-button type="primary" @click="sendMsg()">发送</el-button>
              </div>
            </div>
          </div>
        </el-main>
      </el-container>
    </div>
  </div>
</template>

<script>
let PATH = "/api/im"
export default {
  watch: {
    'userInfo.id': function (newV, oldV) {
      $('#' + newV).css('background-color', '#fcf1f1')
      if (oldV) {
        $('#' + oldV).css('background-color', '')
      }
    }
  },
  computed: {
    uploadData: function () { // 上传文件附带数据
      // 带token
      let o = {}
      let token = localStorage.getItem('token')
      if (token) {
        let t = JSON.parse(token)
        o[t.tokenName] = t.tokenValue
      }
      // 用户数据
      o.userId = this.userInfo.id
      return o;
    },
    imgListAll: function () {
      return this.imgList.map(i => this.sa.getImgPath(i));
    }
  },
  data() {
    return {
      sendImgUrl: PATH + '/sendNewImg',
      sendImgPopoverV: false,
      userList: [], // 用户列表
      p: {//搜索用户
        username:''
      },
      selfUser: this.sa_admin.user,
      content: '',
      // 当前点击用户
      userInfo: {
        avatar: '',
        id: '',
        loginEndTime: '',
        username: '',
        phone: '',
        remark: '',
        sex: '',
        userStatus: ''
      },
      msgList: [],
      imgList: [],
      historyImg: [],
      state:{
        loading:false
      }
    }
  },
  methods: {
    //上传本地文件并发送成功
    uploadSuccess(res){
      if(res.code===200||res.code==='200'){//这个走的是element的请求，没用axios捕获不到，只能正常鉴权了
        this.sendImgPopoverV = false
        this.historyImg.unshift(res.data.content)
        this.userClick(this.userInfo)
      }else if(res.code===403||res.code==='403'){
        this.zm.error("您暂无<发送新图片消息>权限")
      }else{
        this.zm.error(`系统出现了问题：${res.msg}`)
      }
    },
    uploadBef(){

    },
    //发送历史图片
    sendImg(imgPath) { 
      this.sa_admin.$confirm('发送图片?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        let params={
          userId: this.userInfo.id,
          msg: imgPath
        };
        this.request(PATH+'/sendImg',params).then(res=>{
          if(!res){return}
          this.msgList.push({
            id: res.data.id,
            type: 'self',
            msgType: res.data.msgType,
            content: res.data.content
          })
          this.toBottom()
          this.sendImgPopoverV =false
        })
      }).catch(() => {
      });
    },
    //发送消息
    sendMsg() { 
      if (this.content.trim() === '') {
        return this.$message.warning('不可发送空消息')
      }
      let params={
        userId: this.userInfo.id,
        msg: this.content
      };
      this.request(PATH+'/send',params).then(res=>{
        if(!res){return}
        this.msgList.push({
          id: res.data.id,
          type: 'self',
          msgType: res.data.msgType,
          content: res.data.content
        })
        this.toBottom()
        this.content = ''
      })
    },
    //加载左边用户信息栏
    online(flag) {
      this.request(PATH+'/online').then(res=>{
        if(!res){return}
        this.userList = res.data.users
        this.historyImg = res.data.urlList
        if (flag === 'f5'){
          this.userClick(res.data[0])
        }
      })
    },
    //点击左侧用户信息加载右边的信息
    userClick(data) { 
      if (data){
        this.state.loading=true
        this.userInfo = data;
        this.request(PATH+'/userClick?userId='+data.id).then(res=>{
          if(!res){return}
          this.imgList = res.data.imgList;
          this.msgList = res.data.msgList;
          this.state.loading=false
          this.toBottom()
        })
      }
    },
    //聊天框滚动到最底下
    toBottom() { 
      this.$nextTick(()=>{
        let mb = $('#msg-body');
        let scrollHeight = mb.prop("scrollHeight");
        mb.animate({scrollTop: scrollHeight}, scrollHeight);
      })
    }
  },
  created() {
    this.online('f5')
    this.zm.wsCallback.set('receive_msg', (data, ws) => {
      this.online('f5')
    })
  }
}
</script>

<style scoped>
/*如需隐藏滚动条，解除下面css注释即可*/
/*.user-list::-webkit-scrollbar {
  display: none;
}
.user-list{
  scrollbar-width: none;

}*/
.user-item {
  display: flex;
  align-items: center;
  margin: 3px;
  cursor: pointer;
  border-radius: 5px;
  background-color: #ffffff
}

.el-main {
  border-radius: 5px;
  background-color: #ffffff;
  padding: 10px;
}

.badge-item {
  margin-top: 5px;
}

.up-img:hover {
  color: #4cbbde;
}

.user-item:hover {
  background-color: #fcf1f1;
}

.el-textarea textarea {
  font-weight: 600;
}
/*聊天图片样式*/
.chatImg {
  width: 100%;
	height: 100%;
	object-fit: contain;
}
</style>
